package com.abl.core.common.util;

import com.alibaba.fastjson2.JSONObject;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;

/**
 * 通用http发送方法
 */
@Slf4j
@Component
public class HttpKit {

    private static RestTemplate restTemplate;

    @Resource
    public void setMyService(RestTemplate restTemplate) {
        HttpKit.restTemplate = restTemplate;
    }

    public static String doGet(String url) {
        HttpHeaders headers = new HttpHeaders();
        headers.set(HttpHeaders.ACCEPT_CHARSET, StandardCharsets.UTF_8.toString());
        return doGet(url, headers);
    }

    public static String doGet(String url, HttpHeaders headers) {
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, new HttpEntity<>(headers), String.class);
        log.info("\nGET请求\n地址：{}\n请求头：{}\n返回信息：{}", url, headers, response);
        return response.getBody();
    }

    public static String doPostForm(String url, HashMap<String, String> params) {
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set(HttpHeaders.ACCEPT_CHARSET, StandardCharsets.UTF_8.toString());
        return doPost(url, headers, params);
    }

    public static String doPostJSON(String url, HashMap<String, String> params) {
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.set(HttpHeaders.ACCEPT_CHARSET, StandardCharsets.UTF_8.toString());
        headers.setContentType(MediaType.APPLICATION_JSON);
        return doPost(url, headers, params);
    }

    public static String doPost(String url, HttpHeaders headers, HashMap<String, String> params) {
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, new HttpEntity<>(params, headers), String.class);
        log.info("\nPOST表单方式请求\n地址：{}\n请求头：{}\n参数：{}\n返回信息：{}", url, headers, JSONObject.toJSONString(params), response);
        return response.getBody();
    }

}